/**
 * shopmobile for tpshop
 * ============================================================================
 * 版权所有 2015-2099 深圳搜豹网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.tp-shop.cn
 * ——————————————————————————————————————
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author: 飞龙  wangqh01292@163.com
 * Date: @date 2015年11月3日 下午10:04:49
 * Description:产品列表
 *
 * @version V1.0
 */
package org.gangcai.mac.shop.activity;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.SPUtils;
import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.orhanobut.dialogplus.DialogPlus;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.gangcai.mac.shop.R;

import org.gangcai.mac.shop.adapter.SPProductListAdapter;
import org.gangcai.mac.shop.adapter.SPProductListAdapter.ItemClickListener;
import org.gangcai.mac.shop.api.AppAPI;
import org.gangcai.mac.shop.base.SPBaseActivity;
import org.gangcai.mac.shop.bean.CateGoodsBean;
import org.gangcai.mac.shop.bean.CateGoodsBean.GoodsDBean;
import org.gangcai.mac.shop.bean.CommonResonseBean;
import org.gangcai.mac.shop.bean.SPCategory;
import org.gangcai.mac.shop.bean.SPProductCondition;
import org.gangcai.mac.shop.bean.SPShopOrder;
import org.gangcai.mac.shop.common.BaseApplication;
import org.gangcai.mac.shop.common.SPMobileConstants;
import org.gangcai.mac.shop.fragment.SPProductListFilterFragment;
import org.gangcai.mac.shop.manager.RetrofitManagers;
import org.gangcai.mac.shop.oberver.CommonObserver;
import org.gangcai.mac.shop.utils.PromptDialogUtils;
import org.gangcai.mac.shop.views.SPProductFilterTabView;
import org.gangcai.mac.shop.views.SPProductFilterTabView.OnSortClickListener;
import org.json.JSONObject;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import me.leefeng.promptlibrary.PromptDialog;

/*import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.State;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.extras.SoundPullEventListener;*/

/**
 * @author 飞龙
 * http://www.tpshop.com/index.php/Api/Goods/goodsInfo?id=1
 */
public class SPProductListActivity extends SPBaseActivity implements ItemClickListener, OnSortClickListener {
    private PromptDialog prompDialog;
    private String TAG = "SPProductListActivity";
    private String catIDString = "0";
    private String search_intro = "best";
    private static SPProductListActivity instance;

    PtrClassicFrameLayout ptrClassicFrameLayout;
    ListView mListView;
    TextView syntheisTxtv;
    TextView salenumTxtv;
    TextView priceTxtv;
    EditText searchText;//搜索文本框
    ImageView backImgv;    //返回键

    SPProductListAdapter mAdapter;

    SPProductFilterTabView mFilterTabView;

    DrawerLayout mDrawerLayout;

    String mSort = "";            //排序字段
    String mOrder = "asc";        //asc: 升序, desc:降序
    int mPageIndex = 1;        //当前第几页
    boolean mIsMaxPage;            //是否最大页数

    String mHref;                //请求URL
    SPShopOrder mShopOrder;        //排序实体
    List<GoodsDBean> mProducts;
    SPProductListFilterFragment mFilterFragment;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SPMobileConstants.MSG_CODE_FILTER_CHANGE_ACTION:
                    if (msg.obj != null) {
                        mHref = msg.obj.toString();
                        refreshData();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle bundle) {
        //super.setCustomerTitle(true, true , "商品列表");
        super.onCreate( bundle );
        /** 自定义标题栏 , 执行顺序必须是一下顺序, 否则无效果.  */
        requestWindowFeature( Window.FEATURE_CUSTOM_TITLE );
        setContentView( R.layout.product_list );
        getWindow().setFeatureInt( Window.FEATURE_CUSTOM_TITLE, R.layout.product_list_header );
        /** 自定义标题栏  */
        Intent intent = getIntent();
        if (intent != null) {
            catIDString = intent.getStringExtra( "cat_id" );
            search_intro = intent.getStringExtra( "search_intro" );
        }
        prompDialog = PromptDialogUtils.getPrompDialog( this );
        //过滤标题
        super.init();
        refreshData();
        instance = this;
    }

    public static SPProductListActivity getInstance() {
        return instance;
    }

    @Override
    public void initSubViews() {

        WindowManager wm = (WindowManager) getBaseContext().getSystemService( Context.WINDOW_SERVICE );

        mFilterTabView = (SPProductFilterTabView) findViewById( R.id.filter_tabv );
        mFilterTabView.setOnSortClickListener( this );
        ptrClassicFrameLayout = (PtrClassicFrameLayout) this.findViewById( R.id.test_list_view_frame );
        mListView = (ListView) findViewById( R.id.pull_product_listv );
        View emptyView = findViewById( R.id.empty_lstv );
        mListView.setEmptyView( emptyView );

        //综合
        syntheisTxtv = (TextView) findViewById( R.id.sort_button_synthesis );
        salenumTxtv = (TextView) findViewById( R.id.sort_button_salenum );
        priceTxtv = (TextView) findViewById( R.id.sort_button_price );

        searchText = (EditText) findViewById( R.id.search_edtv );
        searchText.setFocusable( false );
        searchText.setFocusableInTouchMode( false );
        backImgv = (ImageView) findViewById( R.id.title_back_imgv );

        mDrawerLayout = (DrawerLayout) findViewById( R.id.drawerlayout );

        BaseApplication.getInstance().productListType = 1;
        mFilterFragment = (SPProductListFilterFragment) getSupportFragmentManager().findFragmentById( R.id.right_rlayout );

        mDrawerLayout.setDrawerListener( new DrawerLayout.SimpleDrawerListener() {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened( drawerView );
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed( drawerView );
            }

            @Override
            public void onDrawerStateChanged(int newState) {
                super.onDrawerStateChanged( newState );
            }
        } );
    }


    @Override
    public void initData() {
        mPageIndex = 1;
        mIsMaxPage = false;
        mAdapter = new SPProductListAdapter( this, this );
        mListView.setAdapter( mAdapter );

        ptrClassicFrameLayout.postDelayed( new Runnable() {

            @Override
            public void run() {
                //ptrClassicFrameLayout.autoRefresh(true);
            }
        }, 150 );

        ptrClassicFrameLayout.setPtrHandler( new PtrDefaultHandler() {

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //下拉刷新
                refreshData();
            }
        } );

        ptrClassicFrameLayout.setOnLoadMoreListener( new OnLoadMoreListener() {

            @Override
            public void loadMore() {
                //上拉加载更多
                loadMoreData();

            }
        } );
    }


    /**
     * 加载数据
     * @Description: 加载数据
     * @return void    返回类型
     * @throws
     */
    public void refreshData() {

        mPageIndex = 1;
        mIsMaxPage = false;
        SPProductCondition conditioon = new SPProductCondition();

        if (catIDString != null) {
            //获取某个分类的ID
            conditioon.categoryID = catIDString;
        }

        conditioon.href = mHref;
        conditioon.page = mPageIndex;
        conditioon.orderby = mSort;
        conditioon.orderdesc = mOrder;
        if (search_intro != null) {
            RetrofitManagers.getInstance().create( AppAPI.class ).search_intro( "search", search_intro, mOrder )
                    .observeOn( AndroidSchedulers.mainThread() )
                    .subscribe( new CommonObserver<CateGoodsBean>( prompDialog ) {
                        @Override
                        public void onSuccess(CateGoodsBean value) {
                            if (value.getCode() == 101) {
                                mProducts = value.getInfo();
                                if (mProducts.size() > 0) {
                                    mAdapter.setData( mProducts );
                                    mAdapter.notifyDataSetChanged();
                                }
                                mIsMaxPage = false;
                                ptrClassicFrameLayout.setLoadMoreEnable( true );
                            }
                        }


                    } );
        } else {
            RetrofitManagers.getInstance().create( AppAPI.class ).goodslist( "goods_list", catIDString, mOrder )
                    .observeOn( AndroidSchedulers.mainThread() )
                    .subscribe( new CommonObserver<CateGoodsBean>( prompDialog ) {
                        @Override
                        public void onSuccess(CateGoodsBean value) {
                            if (value.getCode() == 101) {
                                mProducts = value.getInfo();
                                if (mProducts.size() > 0) {
                                    mAdapter.setData( mProducts );
                                    mAdapter.notifyDataSetChanged();
                                }
                                mIsMaxPage = false;
                                ptrClassicFrameLayout.setLoadMoreEnable( true );
                            }
                        }


                    } );
        }
    }


    /**
     * 加载数据
     * @Description: 加载数据
     * @return void    返回类型
     * @throws
     */
    public void loadMoreData() {

        if (mIsMaxPage) {
            return;
        }
        mPageIndex++;

        SPProductCondition conditioon = new SPProductCondition();

        if (catIDString != null) {
            //获取某个分类的ID
            conditioon.categoryID = catIDString;
        }

        conditioon.href = mHref;
        conditioon.page = mPageIndex;
        conditioon.orderby = mSort;
        conditioon.orderdesc = mOrder;
//		try {
//			showLoadingToast("正在加载商品数据");
//			SPShopRequest.getProductList(conditioon, new SPSuccessListener() {
//				@Override
//				public void onRespone(String msg, Object data) {
//					hideLoadingToast();
//					try {
//						mDataJson = (JSONObject) data;
//						if (mDataJson != null) {
//							mShopOrder = (SPShopOrder) mDataJson.get("order");
//							List<GoodsDBean> results = (List<GoodsDBean>) mDataJson.get("product");
//							if (results != null && mProducts != null) {
//								mProducts.addAll(results);
//								mAdapter.setData(mProducts);
//								mAdapter.notifyDataSetChanged();
//							} else if (results == null) {
//								ptrClassicFrameLayout.setLoadMoreEnable(false);
//							}
//							if (SPProductListFilterFragment.getInstance(mHandler)!=null){
//								SPProductListFilterFragment.getInstance(mHandler).setDataSource(mDataJson);
//							}
//							mIsMaxPage = false;
//							ptrClassicFrameLayout.setLoadMoreEnable(true);
//						}else{
//							mIsMaxPage = true;
//							ptrClassicFrameLayout.setLoadMoreEnable(false);
//						}
//						refreshView();
//					} catch (Exception e) {
//						e.printStackTrace();
//					}
//				}
//			}, new SPFailuredListener() {
//				@Override
//				public void onRespone(String msg, int errorCode) {
//					hideLoadingToast();
//					showToast(msg);
//					ptrClassicFrameLayout.loadMoreComplete(true);
//					mPageIndex--;
//				}
//			});
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
    }

    @Override
    public void initEvent() {
        searchText.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//				Intent intent = new Intent(SPProductListActivity.this , SPSearchCommonActivity.class);
//				SPProductListActivity.this.startActivity(intent);
            }
        } );
        backImgv.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SPProductListActivity.this.finish();
            }
        } );
    }


    public void startupActivity(String goodsID) {
        Intent intent = new Intent( this, SPShopDetailActivity.class );
        intent.putExtra( "goodsID", goodsID );
        startActivity( intent );
    }


    @Override
    public void onItemClickListener(GoodsDBean product) {
        startupActivity( product.getGoods_id() );
    }

    @Override
    public void onChildClickListener(String goods_id) {
        String uidString=SPUtils.getInstance().getString("uid", "");
        if(uidString.length()>0){
            createCarts(goods_id);
        }else{
            Intent loginIntent = new Intent( SPProductListActivity.this, LoginActivity.class );
            startActivity( loginIntent );
        }
    }

    @Override
    public void onFilterClick(SPProductFilterTabView.ProductSortType sortType) {

        switch (sortType) {
            case composite:
                if (mShopOrder != null) {
                    mHref = mShopOrder.getDefaultHref();
                }
                break;
            case salenum:
                if (mShopOrder != null) {
                    mHref = mShopOrder.getSaleSumHref();
                }
                break;
            case price:
                if (mShopOrder != null) {
                    mHref = mShopOrder.getPriceHref();
                }
                break;
            case filter:
                openRightFilterView();
                return;
        }
        refreshData();
    }

    public void openRightFilterView() {
        mDrawerLayout.openDrawer( Gravity.RIGHT );
        mDrawerLayout.setDrawerLockMode( DrawerLayout.LOCK_MODE_UNLOCKED, Gravity.RIGHT );
    }

    public void refreshView() {
        if (mShopOrder != null && mShopOrder.getSortAsc() != null) {
            if (mShopOrder.getSortAsc().equalsIgnoreCase( "desc" )) {
                mFilterTabView.setSort( true );
            } else {
                mFilterTabView.setSort( false );
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        searchText.setFocusable( false );
        searchText.setFocusableInTouchMode( false );
    }

    private void createCarts(String goods_id) {
        RetrofitManagers.getInstance().create(AppAPI.class).carts_create("carts/create", SPUtils.getInstance().getString("uid"),goods_id,"1")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CommonObserver<CommonResonseBean>(prompDialog) {
                    @Override
                    public void onSuccess(CommonResonseBean value) {
                        if (value.getCode() == 101) {
                            showCartsDialog();
                        }else{
                            Toast.makeText(SPProductListActivity.this, "系统繁忙，请稍后再试...", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void showCartsDialog() {
        final DialogPlus dialog = DialogPlus.newDialog( this )
                .setGravity( Gravity.CENTER )
                .setContentBackgroundResource( android.R.color.transparent )
                .setContentWidth( ViewGroup.LayoutParams.WRAP_CONTENT )  // or any custom width ie: 300
                .setContentHeight( ViewGroup.LayoutParams.WRAP_CONTENT )
                .setContentHolder( new com.orhanobut.dialogplus.ViewHolder( R.layout.cartscreate_dialog_layout ) )
                .setExpanded( false )  // This will enable the expand feature, (similar to android L share dialog)
                .create();
        View holderView = dialog.getHolderView();
        holderView.findViewById( R.id.mcart_confirm_btn1 ).setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        } );
        holderView.findViewById( R.id.mcart_confirm_btn2 ).setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getIntent().putExtra("action", "flow"); //将计算的值回传回去
                //通过intent对象返回结果，必须要调用一个setResult方法，
                //setResult(resultCode, data);第一个参数表示结果返回码，一般只要大于1就可以，但是
                setResult(2, getIntent());
                finish();
                dialog.dismiss();
            }
        } );

        dialog.show();


    }

}
